package org.ihelpuoo.filepool;

import java.io.File;
import java.io.IOException;

import org.ihelpuoo.core.Factory;
import org.ihelpuoo.io.FileUtils;
import org.ihelpuoo.lang.NutException;
import org.ihelpuoo.util.Properties;

public class FilePoolImpl extends Factory implements FilePool
{

	private File	home;

	@Override
	public void init(Properties config) throws NutException
	{
		super.init(config);
		home = FileUtils.findFile(config.getString("home"));
		if (null == home || !home.isDirectory())
			throw new NutException("FilePool expect a directory as home!");
	}

	public File copyFileToPool(int fileId, File src) throws IOException
	{
		File target = FileUtils.getFileById(fileId,home,FileUtils.getExtension(src));
		if (target.exists())
			FileUtils.deleteFile(target);

		if (FileUtils.copyFile(src,target))
			return target;
		return null;
	}

	public boolean deleteFile(int fileId, String extension)
	{
		File target = getFile(fileId,extension);
		if (target.exists())
			return FileUtils.deleteFile(target);

		return false;
	}

	public File getFile(int fileId, String extension)
	{
		return FileUtils.getFileById(fileId,home,extension);
	}

	public boolean hasFile(int fileId, String extension)
	{
		return getFile(fileId,extension).exists();
	}

	public File moveFileToPool(int fileId, File src) throws IOException
	{
		File target = FileUtils.getFileById(fileId,home,FileUtils.getExtension(src));
		if (target.exists())
			FileUtils.deleteFile(target);
		if (FileUtils.moveTo(src,target))
			return target;
		return null;
	}

	public File getHome()
	{
		return home;
	}

	public void setHome(File home)
	{
		this.home = home;
	}

	@Override
	public void depose() throws NutException
	{
	}

}
